package com.cskaoyan.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Description:自定义Authenticator，用于分发不同登录类型的Realm
 * @Author: Pinocao
 * @CreateTime: 2022-11-22  17:11
 * @Version: 1.0
 */
@Component
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomToken customToken = (CustomToken) authenticationToken;
        String loginType = customToken.getLoginType();
        // 获取所有的realms
        Collection<Realm> realms = getRealms();
        // 新建List用于存储匹配的Realm
        ArrayList<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
            // System.out.println(realm.getName());
            if (realm.getName().contains("Web") && "webLogin".equals(loginType)) {
                typeRealms.add(realm);
            }
            if (realm.getName().contains("Wx") && "wxLogin".equals(loginType)) {
                typeRealms.add(realm);
            }
        }
        // 判断是单realm还是多realm
        if (typeRealms.size() == 1)
            return doSingleRealmAuthentication(typeRealms.iterator().next(), customToken);
        else
            return doMultiRealmAuthentication(typeRealms, customToken);
    }
}